export default class FRequest {
  constructor () {

  }
  config = {
    baseUrl: "",
    isJson: false,
    headers: {}
  }
  interceptor = {
    request: (init) => {
      return init
    },
    response: {
      convert(res) {
        return res.response
      },
      next(res) {
        return res
      }
    }
  }
  getRealUrl (url) {
    if (url.startsWith("/")) {
      url = url.slice(1)
    }
    this.config.baseUrl = this.config.baseUrl ?? ""
    if (this.config.baseUrl.endsWith("/")) {
      this.config.baseUrl = this.config.baseUrl.endsWith.slice(0, -1)
    }
    return this.config.baseUrl + "/" + url;
    
  }
  post(url, params={}, headers={}) {
    url = this.getRealUrl(url)
    if (this.config.isJson == true && !(params instanceof FormData)) {
      params = JSON.stringify(params)
    }
    headers = {
      ...(this.config.headers ?? {}),
      ...headers
    }
    return this.request(url, {
      method: "POST",
      headers: headers,
      body: params
    })
  }
  request (url, init) {
    return new Promise( (resolve, reject) => {
      init = this.interceptor.request(init)
      const xhr = new XMLHttpRequest()
      xhr.open(init.method, url, true)
      for (let key in init.headers) {
        xhr.setRequestHeader(key, init.headers[key])
      }
      xhr.onload = () => {
        const response = this.interceptor.response.convert(xhr)
        this.interceptor.response.next(response)
        resolve(response)
      }
      xhr.send(init.body ?? null)
    })
  }
  httpBuildQuery (params) {
    let strArray = []
    for (let key in params) {
      strArray.push(key + '=' + params[key])
    }
    return strArray.join("&")
  }
  get(url, params={}, headers={}) {
    url = this.getRealUrl(url)
    let symbol = "?"
    if (url.endsWith("?") || url.endsWith("&")) {
      symbol = ""
    } else if (url.includes("?")) {
      symbol = "&"
    }
    url = url + symbol + this.httpBuildQuery(params)
    headers = {
      ...(this.config.headers ?? {}),
      ...headers
    }
    return this.request(url, {
      method: "GET",
      headers: headers,
    })
  }
}